"""主窗口UI模块"""

from datetime import datetime
from typing import List, Optional
from PySide6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
    QListWidget, QListWidgetItem, QLabel, QPushButton,
    QTextEdit, QScrollArea, QSplitter, QMessageBox,
    QMenu, QMenuBar, QStatusBar, QFrame, QLineEdit
)
from PySide6.QtCore import Qt, QSize, Signal, QTimer, QPropertyAnimation, QEasingCurve
from PySide6.QtGui import QFont, QIcon, QPixmap, QAction, QCloseEvent, QPainter, QPen
import base64

from .database import ClipboardDatabase, ClipboardItem
from .clipboard_monitor import ClipboardMonitor, ClipboardUtils
from .clipboard_list_widget import ClipboardListWidget
from .detail_panel import CollapsibleDetailPanel
from .clipboard_item_widget import ClipboardItemWidget
from .search_widget import SearchWidget


class MainWindow(QMainWindow):
    """主窗口"""
    
    # 信号定义
    hide_to_tray = Signal()
    toggle_topmost = Signal()  # 新增置顶信号
    
    def __init__(self, database: ClipboardDatabase, monitor: ClipboardMonitor):
        super().__init__()
        self.database = database
        self.monitor = monitor
        self.is_topmost = False  # 记录窗口是否置顶
        self.topmost_action = None  # 保存置顶菜单项的引用
        self.setup_ui()
        self.setup_connections()
        self.clipboard_list.load_items()  # 加载剪切板项目
        
        # 设置窗口属性
        self.setWindowTitle("智能剪切板")
        self.setMinimumSize(400, 400)
        self.resize(500, 600)  # 收缩状态的初始高度
        
        # 禁用最大化按钮，保留关闭按钮
        self.setWindowFlags(
            Qt.Window | 
            Qt.WindowTitleHint | 
            Qt.WindowSystemMenuHint | 
            Qt.WindowMinimizeButtonHint | 
            Qt.WindowCloseButtonHint
        )
        
        # 状态栏更新定时器
        self.status_timer = QTimer()
        self.status_timer.timeout.connect(self.update_status)
        self.status_timer.start(5000)  # 每5秒更新一次状态
    
    def setup_ui(self):
        """设置UI"""
        # 创建中央widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout()
        central_widget.setLayout(main_layout)
        
        # 列表部分
        list_frame = QFrame()
        list_layout = QVBoxLayout()
        list_frame.setLayout(list_layout)
        
        # 剪切板项目列表
        self.clipboard_list = ClipboardListWidget(self.database)
        self.clipboard_list.item_selected.connect(self.on_selection_changed)
        self.clipboard_list.item_double_clicked.connect(self.on_item_double_clicked)
        list_layout.addWidget(self.clipboard_list)
        
        # 可折叠的详情面板（包含搜索组件）
        self.detail_panel = CollapsibleDetailPanel()
        self.detail_panel.main_window = self  # 设置主窗口引用
        
        # 获取操作按钮
        self.copy_button, self.delete_button, self.clear_button = self.detail_panel.get_buttons()
        
        # 添加到主布局
        main_layout.addWidget(list_frame, 1)
        main_layout.addWidget(self.detail_panel)
        
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.update_status()
        
        # 设置样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #ffffff;
            }
            QTextEdit {
                border: 1px solid #dee2e6;
                border-radius: 6px;
                background-color: #f8f9fa;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 11px;
            }
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
            QPushButton:disabled {
                background-color: #6c757d;
                color: #adb5bd;
            }
        """)
    
    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件(&F)")
        
        hide_action = QAction("隐藏到托盘(&H)", self)
        hide_action.setShortcut("Ctrl+H")
        hide_action.triggered.connect(self.hide_to_tray_slot)
        file_menu.addAction(hide_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出(&X)", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu("编辑(&E)")
        
        refresh_action = QAction("刷新(&R)", self)
        refresh_action.setShortcut("F5")
        refresh_action.triggered.connect(self.clipboard_list.refresh)
        edit_menu.addAction(refresh_action)
        
        # 搜索功能
        search_action = QAction("搜索(&S)", self)
        search_action.setShortcut("Ctrl+F")
        search_action.triggered.connect(self.focus_search)
        edit_menu.addAction(search_action)
        
        clear_search_action = QAction("清除搜索(&C)", self)
        clear_search_action.setShortcut("Ctrl+Shift+F")
        clear_search_action.triggered.connect(self.clear_search)
        edit_menu.addAction(clear_search_action)
        
        edit_menu.addSeparator()
        
        clear_action = QAction("清空历史(&H)", self)
        clear_action.triggered.connect(self.clear_history)
        edit_menu.addAction(clear_action)
        
        edit_menu.addSeparator()
        
        # 置顶功能
        topmost_text = "📌 取消置顶(&T)" if self.is_topmost else "📌 窗口置顶(&T)"
        self.topmost_action = QAction(topmost_text, self)
        self.topmost_action.setShortcut("Ctrl+T")
        self.topmost_action.triggered.connect(self.on_toggle_topmost)
        edit_menu.addAction(self.topmost_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助(&H)")
        
        about_action = QAction("关于(&A)", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def setup_connections(self):
        """设置信号连接"""
        # 列表信号连接在setup_ui中已经设置
        
        # 按钮点击
        self.copy_button.clicked.connect(self.copy_selected_item)
        self.delete_button.clicked.connect(self.delete_selected_item)
        self.clear_button.clicked.connect(self.clear_history)
        
        # 搜索功能 - 使用详情面板中的搜索组件
        self.detail_panel.search_widget.search_requested.connect(self.perform_search)
        self.detail_panel.search_widget.search_cleared.connect(self.clear_search)
        
        # 监控器信号
        self.monitor.item_added.connect(self.on_item_added)
    
    def perform_search(self, search_text: str):
        """执行搜索"""
        if search_text:
            self.clipboard_list.search(search_text)
            self.status_bar.showMessage(f"搜索: \"{search_text}\" - 找到 {self.clipboard_list.get_item_count()} 项", 3000)
        else:
            self.clear_search()
    
    def clear_search(self):
        """清除搜索"""
        self.clipboard_list.clear_search()
        self.status_bar.showMessage("已清除搜索，显示所有项目", 2000)
    
    def load_clipboard_items(self):
        """加载剪切板项目"""
        self.clipboard_list.load_items()
    
    def on_selection_changed(self):
        """选择变化处理"""
        selected_item = self.clipboard_list.get_selected_item()
        if selected_item:
            self.show_item_details(selected_item)
            self.copy_button.setEnabled(True)
            self.delete_button.setEnabled(True)
            # 不自动展开详情面板，让用户手动控制
        else:
            self.detail_panel.clear_content()
            self.copy_button.setEnabled(False)
            self.delete_button.setEnabled(False)
    
    def on_item_double_clicked(self, item: ClipboardItem):
        """双击项目处理"""
        self.copy_to_clipboard(item)
    
    def show_item_details(self, item: ClipboardItem):
        """显示项目详细信息"""
        if item.content_type == "text":
            self.detail_panel.set_content(item.content, "text")
        elif item.content_type == "image":
            self.detail_panel.set_content(item.content, "image")
        elif item.content_type == "files":
            content = f"文件路径:\n{item.content}"
            self.detail_panel.set_content(content, "text")
        else:
            content = f"[{item.content_type}]\n{item.content}"
            self.detail_panel.set_content(content, "text")
    
    def copy_selected_item(self):
        """复制选中项目"""
        selected_item = self.clipboard_list.get_selected_item()
        if selected_item:
            self.copy_to_clipboard(selected_item)
    
    def copy_to_clipboard(self, item: ClipboardItem):
        """复制到剪切板"""
        try:
            # 设置剪切板内容
            self.monitor.set_clipboard_content(item.content, item.content_type)
            
            # 更新数据库中的时间戳
            self.database.move_to_top(item.id)
            
            # 刷新列表
            self.clipboard_list.refresh()
            
            self.status_bar.showMessage(f"已复制: {ClipboardUtils.get_content_preview(item.content, item.content_type, 30)}", 3000)
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"复制失败: {str(e)}")
    
    def delete_selected_item(self):
        """删除选中项目"""
        selected_item = self.clipboard_list.get_selected_item()
        if selected_item:
                reply = QMessageBox.question(
                    self, "确认删除", 
                f"确定要删除这个项目吗？\n\n{ClipboardUtils.get_content_preview(selected_item.content, selected_item.content_type, 50)}",
                    QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No
                )
                
                if reply == QMessageBox.Yes:
                    if self.clipboard_list.remove_selected_item():
                        self.status_bar.showMessage("项目已删除", 2000)
    
    def clear_history(self):
        """清空历史记录"""
        reply = QMessageBox.question(
            self, "确认清空", 
            "确定要清空所有历史记录吗？\n此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 使用列表类的清空方法
            self.clipboard_list.clear_all_items()
            self.status_bar.showMessage("历史记录已清空", 2000)
    
    def on_item_added(self, item: ClipboardItem):
        """新增项目处理"""
        # 如果当前在搜索状态，检查新项目是否匹配搜索条件
        current_search = self.detail_panel.search_widget.get_search_text()
        if current_search:
            # 检查新项目是否匹配搜索条件
            if (current_search.lower() in item.content.lower() or 
                current_search.lower() in item.content_type.lower()):
                # 匹配搜索条件，重新搜索以包含新项目
                self.clipboard_list.search(current_search)
                self.status_bar.showMessage(f"新增项目匹配搜索: {ClipboardUtils.get_content_preview(item.content, item.content_type, 30)}", 2000)
            else:
                # 不匹配搜索条件，只显示消息
                self.status_bar.showMessage(f"新增项目: {ClipboardUtils.get_content_preview(item.content, item.content_type, 30)} (不匹配当前搜索)", 2000)
        else:
            # 正常状态，刷新列表
            self.clipboard_list.refresh()
        self.status_bar.showMessage(f"新增: {ClipboardUtils.get_content_preview(item.content, item.content_type, 30)}", 2000)
    
    def update_status(self):
        """更新状态栏"""
        stats = self.database.get_stats()
        status_text = f"总计: {stats['total_items']} 项"
        if stats['type_stats']:
            type_info = ", ".join([f"{k}: {v}" for k, v in stats['type_stats'].items()])
            status_text += f" ({type_info})"
        self.status_bar.showMessage(status_text)
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于智能剪切板", 
                         "智能剪切板 v1.0\n\n"
                         "一个功能强大的剪切板管理工具\n"
                         "支持文本、图片、文件路径等多种数据类型\n\n"
                         "使用Python + PySide6开发")
    
    def hide_to_tray_slot(self):
        """隐藏到托盘"""
        self.hide()
        self.hide_to_tray.emit()
    
    def closeEvent(self, event: QCloseEvent):
        """关闭事件处理"""
        # 点击关闭按钮时隐藏到托盘而不是真正关闭
        event.ignore()
        self.hide()
        self.hide_to_tray.emit() 

    def on_toggle_topmost(self):
        """切换窗口置顶状态"""
        # 基础窗口标志（禁用最大化按钮）
        base_flags = (
            Qt.Window | 
            Qt.WindowTitleHint | 
            Qt.WindowSystemMenuHint | 
            Qt.WindowMinimizeButtonHint | 
            Qt.WindowCloseButtonHint
        )
        
        if self.is_topmost:
            # 当前是置顶状态，取消置顶
            self.setWindowFlags(base_flags)
            self.is_topmost = False
            self.topmost_action.setText("📌 取消置顶(&T)")
            self.status_bar.showMessage("已取消窗口置顶", 2000)
        else:
            # 当前不是置顶状态，设置置顶
            self.setWindowFlags(base_flags | Qt.WindowStaysOnTopHint)
            self.is_topmost = True
            self.topmost_action.setText("📌 取消置顶(&T)")
            self.status_bar.showMessage("窗口已设置为置顶显示", 2000)
        
        # 重新显示窗口（setWindowFlags会隐藏窗口）
        self.show()
        self.raise_()
        self.activateWindow()
        
        # 发出信号通知其他组件
        self.toggle_topmost.emit()
    
    def set_topmost_state(self, is_topmost: bool):
        """设置置顶状态（由外部调用）"""
        self.is_topmost = is_topmost
        if self.topmost_action:
            topmost_text = "📌 取消置顶(&T)" if is_topmost else "📌 窗口置顶(&T)"
            self.topmost_action.setText(topmost_text) 

    def focus_search(self):
        """聚焦到搜索框"""
        self.detail_panel.search_widget.focus_search() 